<template>
  <div>
    <!-- 操作工具栏 -->
    <div class="mb-3">
      <el-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['oa:customer:create']"
          >
            新增联系人
          </el-button>
        </div>
    

    <!-- 联系人列表 -->
      <el-table
        v-loading="loading"
        :data="list"
      >
        <el-table-column label="联系人姓名" prop="contactName" align="center" />
        <el-table-column label="联系电话" prop="phone" align="center" />
        <el-table-column label="性别" align="center">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="row.gender || ''" />
          </template>
        </el-table-column>
        <el-table-column label="电子邮箱" prop="email" align="center" />
        <el-table-column label="微信号" prop="wechat" align="center" />
        <el-table-column label="QQ号码" prop="qq" align="center" />
        <el-table-column label="是否首要联系人" prop="isPrimary" align="center" width="130">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.OA_IS_OR_NO" :value="row.isPrimary" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleEdit(row)"
              v-hasPermi="['oa:customer:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(row)"
              v-hasPermi="['oa:customer:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination
        v-model:total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

    <!-- 联系人表单弹窗 -->
    <Dialog
      :title="formTitle"
      v-model="formVisible"
      width="50%"
    >
      <contact-person-form
        ref="formRef"
        v-model="formData"
      />
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="formVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustomerApi, CustomerContactFormVO, ContactPersonRespVO } from '@/api/oa/customer'
import ContactPersonForm from './ContactPersonForm.vue'

defineOptions({ name: 'ContactPersonList' })

const props = defineProps<{
  customerId: number
}>()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(false) // 列表的加载中
const list = ref<ContactPersonRespVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: undefined as number | undefined,
})

// 表单相关
const formRef = ref()
const formVisible = ref(false)
const formTitle = ref('')
const formData = ref<CustomerContactFormVO>({
  customerId: props.customerId,
  contactName: '',
  phone: '',
  gender: undefined,
  email: '',
  wechat: '',
  qq: '',
})

/** 获取联系人列表 */
const getList = async () => {
  if (!queryParams.customerId) {
    list.value = []
    total.value = 0
    return
  }
  loading.value = true
  try {
    const data = await CustomerApi.getCustomerContactPage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    message.error('获取联系人列表失败')
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 监听customerId的变化
watch(() => props.customerId, (newVal) => {
  if (newVal) {
    queryParams.customerId = newVal
    queryParams.pageNo = 1 // 重置页码
    getList()
  } else {
    // 清空列表数据
    list.value = []
    total.value = 0
  }
}, { immediate: true })

/** 处理分页大小变化 */
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

/** 处理页码变化 */
const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  getList()
}

/** 新增联系人 */
const handleAdd = () => {
  formTitle.value = '新增联系人'
  formVisible.value = true
  formData.value = {
    customerId: props.customerId,
    contactName: '',
    phone: '',
    gender: undefined,
    email: '',
    wechat: '',
    qq: '',
    isPrimary: 0
  }
}

/** 编辑联系人 */
const handleEdit = (row: ContactPersonRespVO) => {
  formTitle.value = '编辑联系人'
  formVisible.value = true
  formData.value = { ...row }
}

/** 删除联系人 */
const handleDelete = async (row: ContactPersonRespVO) => {
  try {
    await message.delConfirm()
    await CustomerApi.deleteContactPerson(row.id!)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value.validate()
  
  try {
    if (formData.value.id) {
      // 修改
      await CustomerApi.updateContactPerson(formData.value)
      message.success(t('common.updateSuccess'))
    } else {
      // 新增
      await CustomerApi.createContactPerson(formData.value)
      message.success(t('common.createSuccess'))
    }
    formVisible.value = false
    await getList()
  } catch {}
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.toolbar {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
.dialog-footer {
  text-align: right;
}
</style> 